package com.yuzhantao.collection.sensorflow.response.handle;

import org.jboss.logging.Logger;

import com.alibaba.fastjson.JSON;
import com.yuzhantao.collection.core.message.IMessageHandle;
import com.yuzhantao.collection.sensorflow.message.SensorFlowMessage;
import com.yuzhantao.collection.sensorflow.model.UInfo;
import com.yuzhantao.collection.sensorflow.model.UInfoRepository;

public class TagLinkStateHandle implements IMessageHandle<SensorFlowMessage, Object> {
	protected static final Logger logger = Logger.getLogger(TagLinkStateHandle.class);
	protected final static String CHANNEL_ID = "tag";
	private UInfoRepository uInfoRepository;

	public TagLinkStateHandle(UInfoRepository uInfoRepository) {
		this.uInfoRepository = uInfoRepository;
	}

	@Override
	public boolean isHandle(SensorFlowMessage t) {
		if (this.isVail(t.getSampleUnitId()) && CHANNEL_ID.equals(t.getChannelId())) {
			return true;
		} else {
			return false;
		}
	}

	private boolean isVail(String sampleUnitId) {
		return sampleUnitId.indexOf("u") == 0;
	}

	@Override
	public Object handle(SensorFlowMessage t) {
		int uPosition = Integer.valueOf(t.getSampleUnitId().replaceAll("u-", ""));
		// TODO 由于川师大u位硬件顺序颠倒，顾写顺序修正
		uPosition = 42 - uPosition + 1;
		
		String deviceCode = t.getMonitoringUnitId();
		int state = Integer.valueOf(String.valueOf(t.getValue()));  // 􏲱􏲲􏱡􏱢􏰿0为没有连接标签 􏱊􏳎􏲮􏳋􏲼􏲱􏲲􏰿1􏱊􏳋􏲼􏲷􏲱为连接标签
		
		if(state==1) return null;
		UInfo uInfo = uInfoRepository.findOneByDeviceCodeAndPosition(deviceCode, uPosition);
		if (uInfo == null) return null;
		uInfoRepository.delete(uInfo);
		logger.info("获取到U位已断开连接，并删除库中数据:" + JSON.toJSONString(uInfo));
		return null;
	}

}
